<template>
    <div class="page-container">
        <yh-card class="query-container">
            <yh-form :inline="true" ref="dsForm" :model="reqVO" stripe size="mini" class="query-form" label-width="84px">
                <el-form-item label="条目">
                    <el-select v-model="detailSearchParam.entryCodes" size="mini" filterable multiple collapse-tags clearable placeholder="请选择">
                        <el-option
                            v-for="item in entryDict"
                            :key="item.dictKey"
                            :label="item.dictKey + ' ' + item.dictKeyName"
                            :value="item.dictKey"
                            :title="item.dictKeyName"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="产品">
                    <el-select
                        v-model="detailSearchParam.fundCodes"
                        @visible-change="handleVisibleChange"
                        :filter-method="getFundInfoList"
                        :loading="stockReportState"
                        size="mini"
                        filterable
                        multiple
                        collapse-tags
                        placeholder="请选择"
                    >
                        <el-option v-for="item in fundInfo" :key="item.dictKey" :label="item.dictKey + ' ' + item.dictKeyName" :value="item.dictKey">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="产品组" v-show="queryExtend">
                    <el-select v-model="detailSearchParam.fundGrCodes" size="mini" multiple collapse-tags placeholder="请选择">
                        <el-option v-for="item in fundGroup" :key="item.dictKey" :label="item.dictKey + ' ' + item.dictKeyName" :value="item.dictKey">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="条目组" v-show="queryExtend">
                    <el-select v-model="detailSearchParam.entryGroups" clearable collapse-tags filterable multiple>
                        <el-option
                            v-for="item in entryGroupsDict"
                            :key="item.groupCode"
                            :value="item.groupCode"
                            :label="item.groupCode + ' ' + item.groupName"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <!--
                <el-form-item label="处理状态" v-show="queryExtend">
                    <el-select v-model="detailSearchParam.handleStatuses" clearable collapse-tags filterable multiple>
                        <el-option v-for="(value, key) in handleStatusAll" :key="key" :value="key" :label="value"> </el-option>
                    </el-select>
                </el-form-item>
                -->
                <el-form-item label="证券代码" v-show="queryExtend">
                    <el-select
                        v-model="detailSearchParam.stockCodes"
                        filterable
                        multiple
                        collapse-tags
                        clearable
                        remote
                        :remote-method="getStockCodeList"
                        :loading="selectLoading"
                        placeholder="请输入代码或名称"
                        size="mini"
                        style="width: 100%"
                    >
                        <el-option
                            v-for="item in stockCodeSelectData"
                            :key="item.dictKey"
                            :label="item.dictKey + ' ' + item.dictKeyName"
                            :value="item.dictKey"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注信息" v-show="queryExtend">
                    <el-input v-model="detailSearchParam.comment" style="width: 100%"> </el-input>
                </el-form-item>
                <el-form-item label="处理人" v-show="queryExtend">
                    <el-select v-model="detailSearchParam.handleUsers" style="width: 100%" collapse-tags multiple clearable filterable>
                        <el-option
                            v-for="item in handleUsers"
                            :key="item.dictKey"
                            :value="item.dictCode"
                            :label="item.dictKey + ' ' + item.dictKeyName"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <yh-button type="primary" icon="el-icon-search" @click="query">查询</yh-button>
                    <yh-button icon="el-icon-refresh" @click="resetData">重置</yh-button>
                    <yh-button icon="el-icon-arrow-down" @click="queryExtend = !queryExtend" v-show="!queryExtend">展开</yh-button>
                    <yh-button icon="el-icon-arrow-up" @click="queryExtend = !queryExtend" v-show="queryExtend">隐藏</yh-button>
                </el-form-item>
            </yh-form>
        </yh-card>
        <yh-card class="table-container">
            <yh-toolbar custom>
                <template #buttons>
                    <yh-button type="primary" icon="el-icon-download" @click="loadout">导出</yh-button>
                    <!-- <yh-button type="primary" icon="el-icon-remove-outline">手动计算</yh-button> -->
                </template>
                <template v-slot:tools>
                    <el-popover placement="bottom" width="80" trigger="click" v-model="thresoldTypeVisible">
                        <vxe-table
                            :data="ThresholdTypeDict"
                            @checkbox-all="thresholdTypeSelectChange"
                            @checkbox-change="thresholdTypeSelectChange"
                            style="width: 100%"
                            border
                            ref="popoverTable"
                            show-header-overflow
                            show-overflow
                            :auto-resize="true"
                            resizable
                            row-id="dictKey"
                            :checkbox-config="{ checkRowKeys: thresholdTypeKeys, highlight: true }"
                        >
                            <vxe-column type="checkbox" width="40"> </vxe-column>
                            <vxe-column field="dictKeyName" title="触警状态"> </vxe-column>
                        </vxe-table>
                        <i
                            :class="{ 'el-icon-s-unfold': thresoldTypeVisible, 'el-icon-s-fold': !thresoldTypeVisible }"
                            style="font-size: 22px; line-height: 30px; cursor: pointer; margin-right: 10px"
                            slot="reference"
                        ></i>
                    </el-popover>
                </template>
            </yh-toolbar>
            <yh-table resizable ref="multipleTable" :data="pageVO.list">
                <yh-table-column prop="entryCode" label="条目编号" min-width="105" header-align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.entryCode || '--' }}</span>
                    </template>
                </yh-table-column>
                <yh-table-column prop="entryName" label="条目名称" min-width="100" header-align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.entryName || '--' }}</span>
                    </template>
                </yh-table-column>
                <yh-table-column prop="calculateTime" label="触警时间" min-width="100" header-align="center">
                    <template slot-scope="scope">
                        {{ timeFormat(scope.row.calculateTime) || '--' }}
                    </template>
                </yh-table-column>
                <yh-table-column prop="thresholdValue" label="阈值" min-width="100" header-align="center">
                    <template slot-scope="scope">
                        {{ formatThresholdValue(scope.row) }}
                    </template>
                </yh-table-column>
                <yh-table-column prop="fundNameSt" label="产品名称" min-width="100" header-align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.fundNameSt || '--' }}</span>
                    </template>
                </yh-table-column>
                <yh-table-column prop="thresholdType" label="触警状态" min-width="100" header-align="center">
                    <template slot-scope="scope">
                        <StatusTag :code="scope.row.thresholdType"></StatusTag>
                    </template>
                </yh-table-column>
                <yh-table-column prop="calculateValue" label="实际值" min-width="100" header-align="center">
                    <template slot-scope="scope">
                        <span
                            v-if="scope.row.calculateValue != null"
                            :style="{
                                textDecoration: 'underline',
                                textDecorationColor: ThresholadEntryColor[scope.row.thresholdType],
                                color: ThresholadEntryColor[scope.row.thresholdType],
                                cursor: 'pointer',
                            }"
                            slot="reference"
                            @click="openEntryResultDetail(scope.row)"
                        >
                            {{ formatCalculateValue(scope.row) || '--' }}
                        </span>
                        <span v-else>--</span>
                    </template>
                </yh-table-column>
                <yh-table-column prop="calLogic" label="计算逻辑" min-width="100" header-align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.calLogic || '--' }}</span>
                    </template>
                </yh-table-column>
                <yh-table-column prop="stockCodes" label="证券代码" min-width="100" header-align="center">
                    <template slot-scope="scope">
                        <el-tag size="small" style="" v-if="scope.row.stockInfos != null && scope.row.stockInfos.length > 1" slot="reference">
                            <el-tooltip placement="top">
                                <ul slot="content" style="height: fit-content; max-height: 200px; overflow: auto">
                                    <li :key="item.dictKey" v-for="item in scope.row.stockInfos">
                                        {{ item.dictKey ? item.dictKey + ':' + item.dictKeyName : item.dictCode }}
                                    </li>
                                </ul>
                                <span>{{ scope.row.stockInfos.length + '个证券' }}</span>
                            </el-tooltip>
                        </el-tag>
                        <span v-else-if="scope.row.stockInfos != null && scope.row.stockInfos.length == 1">
                            {{
                                scope.row.stockInfos[0].dictKey
                                    ? scope.row.stockInfos[0].dictKey + ':' + scope.row.stockInfos[0].dictKeyName
                                    : scope.row.stockInfos[0].dictCode
                            }}
                        </span>
                        <span v-else> --</span>
                    </template>
                </yh-table-column>
                <yh-table-column prop="issueInfoName" label="发行人" min-width="100" header-align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.issueInfoName || '--' }}</span>
                    </template>
                </yh-table-column>
                <yh-table-column prop="comment" label="备注信息" min-width="100" header-align="center">
                    <template slot-scope="scope">
                        <el-input
                            v-if="editShow && scope.$index == editRow.index && scope.row == editRow"
                            v-model="scope.row.comment"
                            size="small"
                            @focus="focus(scope.row)"
                            @blur="blur(scope.row)"
                            ref="commentInput"
                        ></el-input>
                        <span v-else>
                            {{ scope.row.comment }}
                        </span>
                    </template>
                </yh-table-column>
                <yh-table-column prop="userInfos" label="处理人" min-width="100" header-align="center">
                    <template slot-scope="scope">
                        {{ handleUserFormatter(scope.row) }}
                    </template>
                </yh-table-column>
            </yh-table>
            <yh-pagination v-bind:pageInfo="pageVO" @pageInfoChange="pageQuery"></yh-pagination>
        </yh-card>
        <div class="panel-subs-popup">
            <ItemRealTimeMonitoringEntryTable v-if="entryVisible" :entry-info="entryInfo" @on-submit="detailTableReturn" />
        </div>
    </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';
import { PageVO } from '@yhfin/biz';
import DictionConstUtil from '@/utils/diction-const-util';
import { checkPermission, numberFormat, numberFormatCIB, timeFormat, unitShow } from '@/utils/tools';
import XEUtils from 'xe-utils';
import { downLoadFile } from '@/utils/request';
import ItemRealTimeMonitoringEntryTable from './item-real-time-monitoring/item-real-time-monitoring-entry-table.vue';
import RiskMonitorTableLayout from './item-real-time-monitoring/risk-monitor-table-layout.vue';
import { getModuleHabit, updateModuleHabit } from './api';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';

@Component({
    name: 'ItemRealTimeMonitoring',
    components: {
        ItemRealTimeMonitoringEntryTable,
        StatusTag,
        RiskMonitorTableLayout,
    },
})
export default class ItemRealTimeMonitoringResult extends Vue {
    private queryExtend = false;
    private entryVisible: boolean = false; // 实际值明细弹窗
    // 明细
    private detailSearchParam = {
        emptyWithoutEntryCodes: false,
        entryCodes: [],
        fundCodes: [],
        fundGrCodes: [],
        handleStatuses: [],
        stockCodes: [],
        comment: '',
        handleUsers: [],
        entryGroups: [],
        thresholdTypes: ['0', '1', '2', '3'],
        paging: {
            currentPage: 1,
            pageSize: 10,
            total: 0,
        },
        sort: '',
    };
    // 符号字典
    private CompareDirection = {
        '0': '>',
        '1': '<',
        '2': '>=',
        '3': '<=',
        '4': '=',
        '5': '<>',
        '6': ' ',
    };
    // 颜色字典
    private ThresholadEntryColor = {
        '0': '#222',
        '1': '#222',
        '2': '#222',
        '3': '#d9001b',
        '4': '#222',
    };
    // 状态
    private handleStatusAll = {
        '1': '待处理',
        '2': '已处理',
        '3': '无需处理',
    };
    Math = Math;
    timeFormat = timeFormat;
    numberFormat = numberFormat;
    // 显示重新连接
    private pageVO: PageVO = new PageVO();
    monitorType: string[] = ['1']; // 后台监控屏计算模式
    private entryDict = [];
    private ThresholdTypeDict;

    thresholdTypeKeys: any[] = ['3']; // 触警状态keys

    private fundInfo = []; // 基金名称列表

    private fundGroup = []; // 基金组名称列表
    private stockCodeSelectData: any[] = []; // 证券代码下拉框数据

    thresoldTypeVisible: boolean = false;
    private selectLoading: boolean = false; // 下拉框加载
    handleUsers: any[] = []; // 处理人
    private entryGroupsDict: any[] = []; // 条目组下拉框

    // 实际值明细
    private entryInfo = {
        title: '',
        entryCode: '',
        fundCode: '',
        fundNameSt: '',
        moduleCode: '',
        isModule: true,
        row: {},
        searchParam: {},
    };
    async created() {}

    async mounted() {
        if (!checkPermission('B_0341')) return;
        await getModuleHabit().then((res: any) => {
            if (res) {
                this.thresholdTypeKeys = res.habitValue;
                if (res.habitValue.includes('-1')) {
                    this.thresholdTypeKeys = [];
                } else {
                    this.thresholdTypeKeys = res.habitValue;
                }
            } else {
                this.thresholdTypeKeys = ['3'];
            }
        });
        // 处理人下拉列表
        this.$axios.post('/instruction/user/select').then((res: any) => {
            this.handleUsers = res;
        });
        this.ThresholdTypeDict = DictionConstUtil.PojoToList(DictionConstUtil.ThresholdType).filter(item => item.dictKey != '4');
        this.getFundInfoList('');
        // 条目组下拉框
        this.$axios.get('/entry/group/list').then((res: any) => {
            this.entryGroupsDict = res || [];
        });

        // 基金组名称列表
        DictionConstUtil.FNFundGroup().then((response: any) => {
            this.fundGroup = response.map(item => {
                return { dictKey: item.fundGroupCode, dictKeyName: item.fundGroupName };
            });
        });
        await this.getEntrySelect();
        this.detailSearchParam.thresholdTypes = this.thresholdTypeKeys;
        this.pageQuery(this.pageVO);
    }

    // 重置数据
    resetData() {
        this.detailSearchParam = {
            entryCodes: [],
            emptyWithoutEntryCodes: false,
            fundCodes: [],
            fundGrCodes: [],
            handleStatuses: [],
            stockCodes: [],
            comment: '',
            handleUsers: [],
            entryGroups: [],
            thresholdTypes: this.thresholdTypeKeys,
            paging: {
                currentPage: 1,
                pageSize: 10,
                total: 0,
            },
            sort: '',
        };
        this.pageVO.pageNum = 1;
        this.pageQuery(this.pageVO);
    }

    getFundInfoList(val) {
        this.$axios
            .get('/fundInfo/list/byUser/like?fundCodeOrName=' + encodeURIComponent(val))
            .then((res: any) => {
                this.fundInfo = res.map(item => {
                    return { dictKey: item.fundCode, dictKeyName: item.fundNameSt };
                });
            })
            .catch(() => {});
    }
    // 处理人
    handleUserFormatter(row) {
        let users = row.userInfos;
        let value = XEUtils.map(users, item => item.dictKeyName);
        return users && users.length ? value.toString() : '--';
    }

    handleVisibleChange(state: boolean) {
        if (!state && !this.fundInfo.length) {
            this.getFundInfoList('');
        }
    }

    // 实际值明细
    detailTableReturn(curPage: number) {
        this.entryVisible = false;
    }

    // 打开弹窗表格
    openEntryResultDetail(obj) {
        this.entryVisible = true;
        let row = obj.row;
        console.info(obj);
        this.entryInfo = {
            title: obj.entryName,
            entryCode: obj.entryCode,
            fundCode: obj.fundCode,
            fundNameSt: obj.fundNameSt || '',
            moduleCode: '',
            isModule: false,
            row: JSON.parse(JSON.stringify(obj)),
            searchParam: this.detailSearchParam,
        };
        if (obj.type == 'module') {
            this.entryInfo.isModule = true;
        } else {
            this.entryInfo.isModule = false;
        }
    }

    // 触警状态改变
    thresholdTypeSelectChange({ selection }) {
        let values = selection;
        this.thresholdTypeKeys = XEUtils.map(values, item => item.dictKey);
        let keys = this.thresholdTypeKeys.length > 0 ? this.thresholdTypeKeys : [-1];
        this.detailSearchParam.thresholdTypes = keys;
        this.pageVO.pageNum = 1;
        this.pageQuery(this.pageVO);
        updateModuleHabit(keys);
    }

    query() {
        this.pageQuery(this.pageVO);
    }
    // 获取明细
    private pageQuery(pageVO: PageVO) {
        this.pageVO.pageNum = pageVO.pageNum;
        this.pageVO.pageSize = pageVO.pageSize;
        this.detailSearchParam.paging.currentPage = this.pageVO.pageNum;
        this.detailSearchParam.paging.pageSize = this.pageVO.pageSize;
        this.$axios({
            url: '/panorama/module/result/detail',
            method: 'post',
            data: this.detailSearchParam,
        }).then((res: any) => {
            res.list &&
                res.list.forEach((item, index) => {
                    this.$set(item, 'index', index);
                });
            this.$set(this.pageVO, 'list', res.list);
            this.$set(this.pageVO, 'total', res.total);
        });
    }
    // 获取明细
    private getEntrySelect() {
        return new Promise((resolve, reject) => {
            this.$axios({
                url: '/dict/entry/select',
                method: 'get',
            }).then((res: any) => {
                this.entryDict = res || [];
                resolve(res);
            });
        });
    }

    // 导出
    loadout() {
        this.$confirm('是否导出风险结果？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            closeOnClickModal: false,
            closeOnPressEscape: false,
        }).then(() => {
            downLoadFile({
                url: '/panorama/module/result/detail/export',
                method: 'post',
                data: this.detailSearchParam,
            });
        });
    }

    // 获取证券代码下拉框数据
    private getStockCodeList(e: string): void {
        this.selectLoading = true;
        this.$axios
            .post('/dict/stock/select', {
                dictKey: e,
                dictKeyName: e,
            })
            .then((res: any) => {
                this.stockCodeSelectData = res || [];
                this.selectLoading = false;
            })
            .catch(() => {
                this.selectLoading = false;
            });
    }

    formatThresholdValue(row): string {
        if (row.thresholdValue || row.thresholdValue == 0) {
            return this.CompareDirection[row.compareType] + numberFormatCIB(row.thresholdValue, row.unit, 'thresholdValue') + unitShow(row.unit);
        }
        return '--';
    }

    formatCalculateValue(row) {
        if (row.calculateValue || row.calculateValue == 0) {
            return numberFormatCIB(row.calculateValue, row.unit) + unitShow(row.unit);
        }
        return '--';
    }
}
</script>

<style lang="scss" scoped>
// 选择框样式
/deep/ .el-select__tags .el-tag.el-tag--info:first-child {
    display: flex;
    align-items: center;
    overflow: hidden;
    max-width: 55%;
    .el-tag__close.el-icon-close {
        top: 0px;
    }
}
/deep/ .el-select__tags .el-tag.el-tag--info:first-child .el-select__tags-text {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
// 下拉列表样式
.el-select-dropdown__item {
    padding: 0 35px 0 20px;
    max-width: 250px;
}

// 表格样式
/deep/.table-container .vxe-table {
    height: calc(100vh - 258px);
    .vxe-table--body-wrapper {
        height: calc(100vh - 298px);
    }
    .fixed-right--wrapper,
    .fixed-left--wrapper {
        height: calc(100vh - 312px);
    }
}
</style>
